<?php


namespace app\api\controller;
header("Access-Control-Allow-Origin:*");
header("Access-Control-Allow-Methods:GET, POST, OPTIONS, DELETE");
header("Access-Control-Allow-Headers:DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type, Accept-Language, Origin, Accept-Encoding");

use app\api\controller\Jwt as Jwt;
use think\Controller;
use think\Db;
use think\Request;

class Auser extends Controller
{

    /**
     *   后台登录
     *dev.ziwudiche.com/api/Auser/login
     * @param string $username  用户名 admin
     * @param string $password 密码  123456
     */
    public function login()
    {

        $username = input('username');
        $password = md5(input('password'));
        $result = Db::name('admin_user')
            ->where('username', $username)
            ->where('pwd', $password)
            ->find();
        if ($result) {
            $token=Jwt::getToken($result['id'],strtotime('+1 day'));
            echo json_encode(["code" => 200, "msg" => '登录成功', 'token' => $token], JSON_UNESCAPED_UNICODE);die();
        } else {
            echo json_encode(["code" => 400102, "msg" => '密码不正确'], JSON_UNESCAPED_UNICODE);die();
        }
    }

    /**
     * 注销登录
     * dev.ziwudiche.com/api/user/logout
     */
    public function logout()
    {
        $token = Request::instance()->header('Authorization');
        $result=Jwt::verifyToken($token);
        if ($result){
            echo json_encode(["code" => 200, "msg" => '注销成功'], JSON_UNESCAPED_UNICODE);die();
        }else{
            echo json_encode(["code" => 404, "msg" => '请先登录'], JSON_UNESCAPED_UNICODE);die();
        }
    }

    /**
     *   后台添加管理员
     *dev.ziwudiche.com/api/Auser/adduser
     * @param string $username  用户名 admin
     * @param string $password 密码  123456
     */
    public function adduser()
    {
        $username = input('username');
        $password = md5(input('password'));
        $ctime = date('Y-m-d H:i:s', time());
        $data=[
          'username'=>$username,
          'pwd'=>$password,
          'createtime'=>$ctime,
        ];
        $result = Db::name('admin_user')->insert($data);
        if ($result) {
            echo json_encode(["code" => 200, "msg" => '创建成功'], JSON_UNESCAPED_UNICODE);die();
        } else {
            echo json_encode(["code" => 404, "msg" => '创建失败'], JSON_UNESCAPED_UNICODE);die();
        }
    }





}